#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
统一账单格式转换引擎
"""

import os
from typing import List
from wechat_parser import Transaction, parse_wechat_bill, batch_auto_categorize
from alipay_parser import parse_alipay_bill
from bank_parser import parse_bank_bill


class BillConverter:
    """统一账单格式转换引擎"""
    
    def __init__(self):
        self.supported_formats = {
            'wechat': '微信账单',
            'alipay': '支付宝账单',
            'bank': '银行账单'
            # 未来可以添加更多平台
            # 'credit_card': '信用卡账单'
        }
    
    def detect_bill_type(self, file_path: str) -> str:
        """检测账单类型"""
        filename = os.path.basename(file_path).lower()
        
        if 'wechat' in filename or '微信' in filename:
            return 'wechat'
        elif 'alipay' in filename or '支付宝' in filename:
            return 'alipay'
        elif 'bank' in filename or '银行' in filename:
            return 'bank'
        else:
            # 尝试通过文件内容检测
            return self._detect_by_content(file_path)
    
    def _detect_by_content(self, file_path: str) -> str:
        """通过文件内容检测账单类型"""
        try:
            # 检查文件扩展名
            _, ext = os.path.splitext(file_path)
            
            if ext.lower() == '.csv':
                # 尝试检测微信账单
                with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                    content = f.read(1000)  # 读取前1000个字符
                    if '微信支付账单' in content:
                        return 'wechat'
                    # 尝试检测银行账单
                    elif '交易时间' in content and ('收/支' in content or '收入/支出' in content):
                        return 'bank'
            elif ext.lower() in ['.xlsx', '.xls']:
                # 尝试检测支付宝账单
                import pandas as pd
                df = pd.read_excel(file_path, header=None, nrows=20)
                
                for _, row in df.iterrows():
                    if '交易时间' in str(row.tolist()) and ('收/支' in str(row.tolist()) or '收入/支出' in str(row.tolist())):
                        # 进一步区分支付宝和银行账单
                        if '支付宝' in str(row.tolist()):
                            return 'alipay'
                        else:
                            return 'bank'
            
            # 默认返回微信账单类型
            return 'wechat'
        except Exception as e:
            # 如果检测失败，默认返回微信账单类型
            return 'wechat'
    
    def convert(self, file_path: str) -> List[Transaction]:
        """转换账单文件为统一格式"""
        try:
            bill_type = self.detect_bill_type(file_path)
            
            if bill_type == 'wechat':
                transactions = parse_wechat_bill(file_path)
                # 对微信账单进行批量自动分类
                remarks = [t.note for t in transactions]
                categories = batch_auto_categorize(remarks)
                # 将分类结果应用到Transaction对象
                for t, (primary_category, secondary_category) in zip(transactions, categories):
                    if secondary_category:
                        t.category = f"{primary_category}|{secondary_category}"
                    else:
                        t.category = primary_category
            elif bill_type == 'alipay':
                transactions = parse_alipay_bill(file_path)
            elif bill_type == 'bank':
                transactions = parse_bank_bill(file_path)
            else:
                raise ValueError(f"不支持的账单类型: {bill_type}")
            
            return transactions
        except Exception as e:
            raise ValueError(f"转换账单文件时出错: {str(e)}")
    
    def get_supported_formats(self) -> dict:
        """获取支持的账单格式"""
        return self.supported_formats


def convert_bill(file_path: str) -> List[Transaction]:
    """便捷函数：转换账单文件为统一格式"""
    converter = BillConverter()
    return converter.convert(file_path)